<template>
  <view class="visitor-management-page">
    <!-- 导航栏 -->
    <u-navbar title="访客管理" back-icon="arrow-left" />
    
    <!-- 筛选区域 -->
    <view class="filter-section">
      <view class="filter-row">
        <u-input
          v-model="filterForm.visitorName"
          placeholder="请输入访客姓名"
          class="filter-input"
          @input="handleSearch"
        />
        <u-button 
          type="primary" 
          text="搜索" 
          size="mini"
          @click="handleSearch"
        />
      </view>
      <view class="filter-row">
        <u-picker
          :show="showStatusPicker"
          :columns="statusColumns"
          @confirm="onStatusConfirm"
          @cancel="showStatusPicker = false"
          title="选择状态"
        />
        <u-input
          v-model="filterForm.statusText"
          placeholder="状态"
          readonly
          @click="showStatusPicker = true"
          class="filter-input"
        />
        <u-input
          v-model="filterForm.visitDate"
          placeholder="访问日期"
          readonly
          @click="showVisitDatePicker = true"
          class="filter-input"
        />
        <u-button 
          type="primary" 
          text="重置" 
          size="mini"
          @click="resetFilter"
        />
      </view>
    </view>

    <!-- 列表区域 -->
    <scroll-view 
      scroll-y="true" 
      class="list-scroll" 
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <view class="list-content">
        <!-- 访客列表 -->
        <view 
          v-for="item in visitorList" 
          :key="item.id"
          class="visitor-card"
          @click="goToVisitorDetail(item.id)"
        >
          <view class="card-header">
            <view class="header-left">
              <text class="visitor-name">{{ item.visitorName }}</text>
              <u-tag 
                :text="getStatusText(item.status)" 
                :type="getStatusType(item.status)" 
                size="mini"
              />
            </view>
            <text class="visit-time">{{ formatTime(item.visitTime) }}</text>
          </view>
          
          <view class="card-content">
            <view class="content-item">
              <u-icon name="user" size="14" color="#666" class="item-icon"></u-icon>
              <text class="item-text">身份证：{{ item.idCard || '未填写' }}</text>
            </view>
            <view class="content-item">
              <u-icon name="phone" size="14" color="#666" class="item-icon"></u-icon>
              <text class="item-text">电话：{{ item.phone || '未填写' }}</text>
            </view>
            <view class="content-item">
              <u-icon name="home" size="14" color="#666" class="item-icon"></u-icon>
              <text class="item-text">访问对象：{{ item.visitTarget || '未填写' }}</text>
            </view>
            <view class="content-item" v-if="item.visitPurpose">
              <u-icon name="file-text" size="14" color="#666" class="item-icon"></u-icon>
              <text class="item-text">访问目的：{{ item.visitPurpose }}</text>
            </view>
            <view class="content-item" v-if="item.leaveTime">
              <u-icon name="clock" size="14" color="#666" class="item-icon"></u-icon>
              <text class="item-text">离开时间：{{ formatTime(item.leaveTime) }}</text>
            </view>
          </view>
          
          <view class="card-footer">
            <view class="duration-info">
              <text class="duration-text">{{ getVisitDuration(item.visitTime, item.leaveTime) }}</text>
            </view>
            
            <view class="action-buttons">
              <u-button 
                v-if="item.status === 1"
                type="success" 
                text="离开"
                size="mini"
                @click.stop="goToVisitorLeave(item.id)"
                class="action-btn"
              />
              <u-button 
                v-else
                type="info" 
                text="详情"
                size="mini"
                @click.stop="goToVisitorDetail(item.id)"
                class="action-btn"
              />
            </view>
          </view>
        </view>
        
        <!-- 空状态 -->
        <view v-if="visitorList.length === 0 && !loading" class="empty-state">
          <u-empty text="暂无访客记录" icon="user-plus" mode="list" />
        </view>
        
        <!-- 加载更多提示 -->
        <view v-if="visitorList.length > 0" class="load-more-tip">
          <text v-if="loading" class="tip-text">加载中...</text>
          <text v-else-if="hasMore" class="tip-text">上拉加载更多</text>
          <text v-else class="tip-text">没有更多数据了</text>
        </view>
      </view>
    </scroll-view>

    <!-- 访客登记按钮 -->
    <view class="register-visitor-button" @click="goToVisitorRegister">
      <u-icon name="plus" color="#fff" size="24"></u-icon>
      <text class="button-text">访客登记</text>
    </view>

    <!-- 日期选择器 -->
    <u-datetime-picker
      :show="showVisitDatePicker"
      v-model="visitDateValue"
      mode="date"
      @confirm="onVisitDateConfirm"
      @cancel="showVisitDatePicker = false"
      title="选择访问日期"
    />
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getVisitorPage } from '@/api/security'

// 响应式数据
const visitorList = ref([])
const loading = ref(false)
const refreshing = ref(false)
const hasMore = ref(true)

// 分页数据
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 筛选表单
const filterForm = reactive({
  visitorName: '',
  status: '',
  statusText: '',
  visitDate: ''
})

// 选择器显示状态
const showStatusPicker = ref(false)
const showVisitDatePicker = ref(false)

// 日期值
const visitDateValue = ref('')

// 选择器数据
const statusColumns = ref([[
  { label: '在访', value: 1 },
  { label: '已离开', value: 2 }
]])

// 页面加载时获取数据
onMounted(() => {
  loadVisitorList()
})

/**
 * 加载访客列表
 */
const loadVisitorList = async (isRefresh = false) => {
  try {
    if (isRefresh) {
      pagination.pageNum = 1
      visitorList.value = []
      hasMore.value = true
    }
    
    loading.value = true
    const params = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      visitorName: filterForm.visitorName,
      status: filterForm.status,
      visitDate: filterForm.visitDate
    }
    
    const response = await getVisitorPage(params)
    if (response.success && response.data) {
      const { records, total } = response.data
      
      if (isRefresh) {
        visitorList.value = records || []
      } else {
        visitorList.value.push(...(records || []))
      }
      
      pagination.total = total || 0
      hasMore.value = visitorList.value.length < pagination.total
    }
  } catch (error) {
    console.error('加载访客列表失败:', error)
    uni.showToast({
      title: '加载失败，请重试',
      icon: 'none'
    })
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

/**
 * 搜索处理
 */
const handleSearch = () => {
  loadVisitorList(true)
}

/**
 * 重置筛选
 */
const resetFilter = () => {
  filterForm.visitorName = ''
  filterForm.status = ''
  filterForm.statusText = ''
  filterForm.visitDate = ''
  loadVisitorList(true)
}

/**
 * 状态选择确认
 */
const onStatusConfirm = (event) => {
  const selectedStatus = event.value[0]
  filterForm.status = selectedStatus.value
  filterForm.statusText = selectedStatus.label
  showStatusPicker.value = false
  loadVisitorList(true)
}

/**
 * 访问日期确认
 */
const onVisitDateConfirm = (event) => {
  filterForm.visitDate = event.value
  showVisitDatePicker.value = false
  loadVisitorList(true)
}

/**
 * 下拉刷新
 */
const onRefresh = () => {
  refreshing.value = true
  loadVisitorList(true)
}

/**
 * 加载更多
 */
const loadMore = () => {
  if (!loading.value && hasMore.value) {
    pagination.pageNum++
    loadVisitorList()
  }
}

/**
 * 获取状态文本
 */
const getStatusText = (status) => {
  const statusMap = {
    1: '在访',
    2: '已离开'
  }
  return statusMap[status] || '未知状态'
}

/**
 * 获取状态类型
 */
const getStatusType = (status) => {
  const typeMap = {
    1: 'primary',
    2: 'success'
  }
  return typeMap[status] || 'info'
}

/**
 * 获取访问时长
 */
const getVisitDuration = (visitTime, leaveTime) => {
  if (!visitTime) return '未开始'
  if (!leaveTime) return '访问中'
  
  const visit = new Date(visitTime)
  const leave = new Date(leaveTime)
  const duration = Math.floor((leave - visit) / (1000 * 60)) // 分钟
  
  if (duration < 60) {
    return `${duration}分钟`
  } else {
    const hours = Math.floor(duration / 60)
    const minutes = duration % 60
    return `${hours}小时${minutes}分钟`
  }
}

/**
 * 格式化时间
 */
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 页面导航方法
const goToVisitorDetail = (id) => {
  uni.navigateTo({
    url: `/pages/property-work/security-management/visitor-detail?id=${id}`
  })
}

const goToVisitorLeave = (id) => {
  uni.navigateTo({
    url: `/pages/property-work/security-management/visitor-leave?id=${id}`
  })
}

const goToVisitorRegister = () => {
  uni.navigateTo({
    url: '/pages/property-work/security-management/visitor-register'
  })
}
</script>

<style lang="scss" scoped>
.visitor-management-page {
  min-height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.filter-section {
  background: white;
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  .filter-row {
    display: flex;
    align-items: center;
    gap: 16rpx;
    margin-bottom: 16rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .filter-input {
      flex: 1;
    }
  }
}

.list-scroll {
  flex: 1;
  min-height: 0;
}

.list-content {
  padding: 20rpx;
}

.visitor-card {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.98);
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    
    .header-left {
      display: flex;
      align-items: center;
      gap: 16rpx;
      
      .visitor-name {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
      }
    }
    
    .visit-time {
      font-size: 24rpx;
      color: #999;
    }
  }
  
  .card-content {
    margin-bottom: 20rpx;
    
    .content-item {
      display: flex;
      align-items: center;
      gap: 12rpx;
      margin-bottom: 12rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .item-icon {
        flex-shrink: 0;
      }
      
      .item-text {
        font-size: 26rpx;
        color: #666;
        line-height: 1.4;
        word-break: break-all;
      }
    }
  }
  
  .card-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .duration-info {
      .duration-text {
        font-size: 24rpx;
        color: #666;
      }
    }
    
    .action-buttons {
      .action-btn {
        min-width: 120rpx;
      }
    }
  }
}

.empty-state {
  padding: 100rpx 0;
  text-align: center;
}

.load-more-tip {
  padding: 30rpx 0;
  text-align: center;
  
  .tip-text {
    font-size: 24rpx;
    color: #999;
  }
}

.register-visitor-button {
  position: fixed;
  bottom: 40rpx;
  right: 40rpx;
  background: linear-gradient(135deg, #ff9500 0%, #ffb84d 100%);
  border-radius: 50rpx;
  padding: 20rpx 30rpx;
  display: flex;
  align-items: center;
  gap: 12rpx;
  box-shadow: 0 4rpx 20rpx rgba(255, 149, 0, 0.4);
  z-index: 999;
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.95);
  }
  
  .button-text {
    color: white;
    font-size: 28rpx;
    font-weight: 600;
  }
}
</style>
